/*
	File: data/scripts/physics_dynamic-mode.nut
	Author: GameStart3d.com
*/

/*!
	@short	PhysicsDynamicMode
	@author	GameStart3d.com
*/
class	PhysicsDynamicMode
{
	kinematic_mode			=	false
	position				=	0
	rotation				=	0
	prev_position			=	0
	velocity				=	0

	anchor					=	0
	timer					=	0.0

	/*!
		@short	OnUpdate
		Called during the scene update, each frame.
	*/

	function	OnPhysicStep(item, dt)
	{
		position = ItemGetWorldPosition(anchor)
		rotation = EulerFromDirection(ItemGetWorldPosition(anchor).Normalize())
		velocity = position - prev_position
		prev_position = clone(position)

		if (!kinematic_mode)
		{
			local	dir = position - ItemGetPosition(item)
			ItemApplyLinearImpulse(item, dir)
		}
	}

	function	OnUpdate(item)
	{
		if (kinematic_mode)
		{
			ItemWake(item)
			ItemPhysicResetTransformation(item, position, rotation)
			ItemSetPosition(item, position)
			ItemSetRotation(item, rotation)
		}

		if (g_clock - timer > SecToTick(Sec(3.0)))
		{
			timer = g_clock
			kinematic_mode = !kinematic_mode
			ItemGetScriptInstance(anchor).label = kinematic_mode?"Kinematic":"Dynamic"

			if (!kinematic_mode)
			{
				ItemWake(item)
				ItemSetLinearVelocity(item, velocity)
				ItemSetAngularVelocity(item, g_zero_vector)
			}
		}

	}

	function	OnRenderUser(item)
	{
		RendererDrawCross(g_render, position)
		RendererDrawLine(g_render, position, position + velocity)
	}

	/*!
		@short	OnSetup
		Called when the item is about to be setup.
	*/
	function	OnSetup(item)
	{
		kinematic_mode = true
		position = ItemGetPosition(item)
		prev_position = clone(position)
		rotation = ItemGetRotation(item)

		velocity = clone(g_zero_vector)
		anchor = SceneFindItem(g_scene, "anchor")
		ItemGetScriptInstance(anchor).label = "Kinematic"
		timer = g_clock
	}
}
